package com.sheng.project.study.cglib;

import cn.hutool.core.lang.UUID;
import org.springframework.cglib.proxy.Dispatcher;
import org.springframework.cglib.proxy.Enhancer;

/**
 * @author liusheng
 * @date 2023/06/29
 */
public class DispatcherTest1 {

    public static void main(String[] args) {
        // Dispatcher 和 LazyLoader 作用很相似，区别是用 Dispatcher 的话每次对增强 bean 进行方法调用都会触发回调。
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(LazyLoaderTest1.UserModel.class);
        // 创建一个 Dispatcher 对象
        Dispatcher dispatcher = new Dispatcher() {
            @Override
            public Object loadObject() throws Exception {
                System.out.println("调用 Dispatcher.loadObject() 方法");
                return new LazyLoaderTest1.UserModel("柳圣 java," + UUID.randomUUID());
            }
        };
        enhancer.setCallback(dispatcher);
        Object proxy = enhancer.create();
        LazyLoaderTest1.UserModel userModel = (LazyLoaderTest1.UserModel) proxy;
        System.out.println("第 1 次调用 say 方法");
        userModel.say();
        System.out.println("第 2 次调用 say 方法");
        userModel.say();
    }

    public static class UserModel {
        private String name;

        public UserModel() {
        }

        public UserModel(String name) {
            this.name = name;
        }

        public void say() {
            System.out.println("你好：" + name);
        }
    }
}
